"""
    **运行处理测试用例
"""
from myblog.dolphinJOB import configHttp
import logging
import re
import json
from myblog.models import DolphinTestProject, DolphinTestRequest, DolphinTestGrouping, DolphinTestHeards
from myblog.dolphinDabases.testDatabase import getSql

logger = logging.getLogger('log')
from myblog.dolphinService.dolphinJOBService.mamhaoJsondict import jsondict


class method():
    def index(self):
        """
        内部方法初始化内容
        :return:
        """
        self.headers = {}
        self.cookies = {}
        self.headers = {}
        self.params = {}
        self.data = {}
        self.url = {}

    def JOBcheckPoint(self, data):
        '''
        :param data:多接口调用发放
        :return:
        '''
        try:
            self.reusltlist = {}
            for i in range(len(data)):
                self.index()
                dictlsit = {}
                data1 = {}
                content = data[i]["content"]
                if data[i]["defaultUrl"] == "customUrl":  # 处理接口地址
                    self.url = data[i]["httpUrl"] + data[i]["url"]
                else:
                    dictUrlList = self.getAddress(requestId=data[i]["defaultUrlReuqestID"], num=1)
                    if str(data[i]["defaultUrl"]) == "1":
                        self.url = dictUrlList["url1"] + data[i]["url"]
                    if str(data[i]["defaultUrl"]) == "2":
                        self.url = dictUrlList["url2"] + data[i]["url"]
                    if str(data[i]["defaultUrl"]) == "3":
                        self.url = dictUrlList["url4"] + data[i]["url"]
                self.herdersHandle(header=data[i]["header"], herderList=data[i]["herderList"])  # 头部信息传参
                for j in range(len(content)):  # 入参处理数据
                    parameter = content[j]["parameter"]
                    value1 = content[j]["value1"]
                    if "[" in value1: value1 = eval(value1)
                    data1[parameter] = value1
                Result = self.mothGet(dataType=data[i]["dataType"], request_mode=data[i]["mode"], data1=data1)  #
                conclusionValue = data[i]["conclusionValue"]
                for x in range(len(conclusionValue)):  # 处理动态取值数据
                    reuslt = Result.json()
                    if conclusionValue[x]["clvaue"] != "" and conclusionValue[x]["num"] != "":
                        clvaueTest = re.split("&|}|{", conclusionValue[x]["clvaue"])[1]
                        self.reusltlist[conclusionValue[x]["clvaue"]] = \
                            jsondict().get_target_value(clvaueTest, reuslt, [])[conclusionValue[x]["num"]]
                    if conclusionValue[x]["clvaue"] != "" and conclusionValue[x]["num"] == "":
                        clvaueTest = re.split("&|}|{", conclusionValue[x]["clvaue"])[1]
                        self.reusltlist[conclusionValue[x]["clvaue"]] = jsondict().get_target_value(clvaueTest, reuslt,
                                                                                                    [])
                dictlsit["data"] = Result.text

                dictlsit["reuslt"] = self.reusltlist
                # 日志记录
                logger.info(("检查点用例名称：%s，用例排序位置：%s") % (data[i]["name"], data[i]["Indexes"]))
                logger.info(("请求接口地址：%s") % (self.url))
                logger.info(("头部信息：%s") % (self.headers))
                logger.info(("请求数据类型：%s") % (data[i]["dataType"]))
                logger.info(("请求类型：%s") % (data[i]["mode"]))
                if data[i]["mode"] == "GET":
                    logger.info(("GET请求入参：%s") % (self.params))
                else:
                    logger.info(("POST请求入参：%s") % (self.data))
                logger.info("请求接口返回内容：%s" % (dictlsit["data"]))
                logger.info("接口响应时间：%ss" % (Result.elapsed.total_seconds()))
                logger.info(("当前接口取值：%s") % (dictlsit["reuslt"]))
            return dictlsit
        except Exception as e:
            logger.error(e)
            return e

    def JOBcheckCaseAll(self, data):
        try:
            self.index()
            self.reusltlist = {}
            data1 = {}  # 传参的值
            addAredss = self.getAddress(requestId=data["request_id"], num=2)
            url1 = addAredss["url1"]
            url2 = addAredss["url2"]
            request_mode = addAredss["request_mode"]
            dataType = data["dataType"]
            paramsData = data["domains"]
            for j in range(len(paramsData)):  # 整理入参数据
                parameter = paramsData[j]["keynew"]
                value = paramsData[j]["value"]
                if "[" in value: value = eval(value)
                data1[parameter] = value

            self.params = data1  # 初始化入参数据
            self.data = data1
            if data["request_other_type"] == True:  # 使用关联接口
                herderList = data["headerData"]
                for i in range(len(data['request_relation_content'])):
                    data['request_relation_content'][i]["herderList"] = herderList
                dictlsit = self.JOBcheckPoint(data['request_relation_content'])
                self.reusltlist.update(dictlsit["reuslt"])

            if data["sqlTrueFlasetype"] == True:  # 使用数据库
                rustulSQL = \
                    self.getSQLValue(id=data["sqlChoice"], sql=data["SQLinput"], SQLMomentum=data["SQLMomentum"],
                                     reusltList=self.reusltlist)[0]
                sqlvalue = data["sqlClusionValue"]
                for z in range(len(sqlvalue)):
                    sqlvaluedict = (list((sqlvalue[z]).values()))[z - 1]  # 整理前段传过来啊的SQL取值
                    sqlvaluedictValue = re.split("&|}|{", sqlvaluedict)[1]  # 去除取值符号
                    for x in range(len(list(rustulSQL.keys()))):  # 数据库响应的SQL的值
                        if list(rustulSQL.keys())[x] == sqlvaluedictValue:  # 判断前段传过来的值和数据库响应的值是否相等
                            self.reusltlist[sqlvaluedict] = list(rustulSQL.values())[x]  # 如果想等就进行赋值给参数化列表

            if data["request_other_type"] == True or data["sqlTrueFlasetype"] == True:
                self.data = data1  # 这一步走了多接口的或者SQL的步骤 所以self.data的入参数据会被上面初始化，这里需要重新生成这个对象
                self.params = data1
                dataNew = self.getModedate(data1)  # 更新入参数据，重新参数化赋值
                self.data.update(dataNew)
                self.params.update(dataNew)

            self.url = url1 + url2  # 整理入参地址
            self.herdersHandle(header=data["headers"], herderList=data["headerData"])  # 整理头部信息

            Result = self.selectType(dataType + request_mode)
            # 日志内容
            logger.info(("用例名称：%s") % (data["case_name"]))
            logger.info(("请求接口地址：%s") % (self.url))
            logger.info(("头部信息：%s") % (self.headers))
            logger.info(("请求数据类型：%s") % (dataType))
            logger.info(("请求类型：%s") % (request_mode))
            logger.info(("是否使用关联接口：%s") % (data["request_other_type"]))
            if request_mode == "GET":
                logger.info(("GET请求入参：%s") % (self.params))
            else:
                logger.info(("POST请求入参：%s") % (self.data))
            logger.info("请求接口返回内容：%s" % (Result.text))
            if data["sqlTrueFlasetype"] == True:
                logger.info("数据库响应结果：%s" % (rustulSQL))
            if self.reusltlist != None:
                logger.info("所使用的参数化的值：%s" % (self.reusltlist))
            logger.info("接口响应时间：%ss" % (Result.elapsed.total_seconds()))

            dictlsitall = {}
            dictlsitall["data"] = Result.text
            dictlsitall["reuslt"] = self.reusltlist
            return dictlsitall
        except EOFError as e:
            logger.info(e)
            return None

    def AssertionResults(self, result, reusltlist, request_result, sqldata):
        '''
        :param result: 接口返回值
        :param reusltlist: 动态接口列表
        :param request_result: 前端传过来断言内容
        :param sqldata :后置sql数据
        :return:返回一个断言数据和一个断言结果
        '''
        try:
            Assertion = "success"
            ParameterValue = []
            dictLsit = {}
            sqlList = []
            clvaue1 = "$"
            for z in range(len(sqldata["sqlClusionValueLast"])):
                listsql = list(dict(sqldata["sqlClusionValueLast"][z]).values())[0]
                for x in range(len(request_result)):
                    if request_result[x]["keynew2"] == listsql:
                        sqlList.append(request_result[x])
            if len(sqlList) == len(request_result) and len(sqlList) > 0:
                request_result = []
            elif len(sqlList) > 0 and len(sqlList) <= len(request_result):
                for x in range(len(sqlList)):
                    request_result.remove(sqlList[x])

            for x in range(len(request_result)):  # 循环断言内容
                if "{" in request_result[x]["keynew2"]:  # 如果键里面是提取键
                    if request_result[x]["keynew2Num"] == "":  # 当前的取值数量等于空时
                        newValue = re.split("&|}|{", request_result[x]["keynew2"])
                        clvaue = newValue[1]
                        clvaue1 = newValue[0]
                        ParameterValue1 = jsondict().get_target_value(clvaue, json.loads(result), [])
                        ParameterValue = clvaue1 + "{" + str(ParameterValue1) + "}"
                    if request_result[x]["keynew2Num"] != "":
                        newValue = re.split("&|}|{", request_result[x]["keynew2"])
                        clvaue = newValue[1]
                        clvaue1 = newValue[0]
                        ParameterValue = jsondict().get_target_value(clvaue, json.loads(result), [])[
                            request_result[x]["keynew2Num"]]  # 把当前提取值复制给新的变量
                        ParameterValue = clvaue1 + "{" + str(ParameterValue) + "}"
                else:
                    ParameterValue = clvaue1 + "{" + request_result[x]["keynew2"] + "}"  # 如果当前不是提取键，这把当前值赋给新的变量
                for y in range(len(list(reusltlist))):  # 循环值穿过来的 动量参数
                    if "{" in request_result[x]["value2"]:  # 当前的动量参数等于是提取值
                        if request_result[x]["value2"] == list(reusltlist.keys())[y]:
                            dictLsit[ParameterValue] = clvaue1 + "{" + str(
                                list(reusltlist.values())[y]) + "}"  # 则和新的变量组合成一个字典
                    else:
                        dictLsit[str(ParameterValue)] = clvaue1 + "{" + request_result[x]["value2"] + "}"  # 否则这把原值
                if len(list(reusltlist)) == 0:
                    dictLsit[str(ParameterValue)] = clvaue1 + "{" + request_result[x]["value2"] + "}"  # 否则这把原值

            if sqldata["sqlTrueFlasetypeLast"] == True:
                SQLReustl = self.getSQLValue(id=sqldata["id"], SQLMomentum=sqldata["SQLMomentum"], sql=sqldata["sql"],
                                             reusltList=reusltlist)[0]
                Sqlreusltlist = {}
                sqlvalue = sqldata["sqlClusionValueLast"]
                for z in range(len(sqlvalue)):
                    sqlvaluedict1 = (list((sqlvalue[z]).values()))[z - 1]  # 整理前段传过来啊的SQL取值
                    sqlvaluedictValue1 = re.split("&|}|{", sqlvaluedict1)[1]  # 去除取值符号
                    for x in range(len(SQLReustl.keys())):  # 数据库响应的SQL的值
                        if list(SQLReustl.keys())[x] == sqlvaluedictValue1:  # 判断前段传过来的值和数据库响应的值是否相等
                            Sqlreusltlist[sqlvaluedict1] = list(SQLReustl.values())[x]  # 如果想等就进行赋值给参数化列表

                for g in range(len(sqlList)):
                    value = ""
                    clvaue1 = re.split("&|}|{", sqlList[g]["keynew2"])[0]
                    for y in range(len(list(Sqlreusltlist))):
                        if sqlList[g]["keynew2"] == list(Sqlreusltlist.keys())[y]:
                            parme = clvaue1 + "{" + str(list(Sqlreusltlist.values())[y]) + "}"
                    for y in range(len(list(reusltlist))):
                        if str(sqlList[g]["value2"]) == list(reusltlist.keys())[y]:
                            value = clvaue1 + "{" + str(list(reusltlist.values())[y]) + "}"
                    if value == "":
                        value = clvaue1 + "{" + sqlList[g]["value2"] + "}"
                    dictLsit[parme] = value
            for z in range(len(list(dictLsit))):
                if list(dictLsit.keys())[z] != list(dictLsit.values())[z]:
                    Assertion = "fail"
            returnList = {}
            returnList["Assertion"] = Assertion
            returnList["AssertionLsit"] = dictLsit
            logger.info("断言数据：%s" % (returnList))
            return returnList
        except Exception as e:
            logger.info(e)
            Assertion = "fail"
            returnList = {}
            returnList["Assertion"] = Assertion
            returnList["AssertionLsit"] = dictLsit
            return returnList


    def mothGet(self, dataType, request_mode, data1):  # 请求数据
        '''
        :param dataType: 请求类型 DATA JSON
        :param request_mode: 请求方式GET POST
        :param data1: 请求数据
        :return: 返回请求对象
        '''
        try:
            for b in range(len(list(data1))):  # 循环请求入参中的个数
                listruet = list(self.reusltlist.keys())  # 获取列表中的键的值
                for c in range(len(listruet)):  # 循环全部键的长度
                    if listruet[c] == str(list(data1.values())[b]):  # 当键的值 等于入参的值相等时
                        dicc = {str(list(data1.keys())[b]): str(self.reusltlist[listruet[c]])}
                        data1.update(dicc)
            self.params = data1
            self.data = data1
            Result = self.selectType(dataType + request_mode)
            return Result
        except BaseException as e:
            logger.error(e)

    def selectType(self, name):
        if name == "dataGET": Result = configHttp.ConfigHttp.dataget(self)
        if name == "dataPOST": Result = configHttp.ConfigHttp.datapost(self)
        if name == "jsonGET": Result = configHttp.ConfigHttp.jsonget(self)
        if name == "jsonPOST": Result = configHttp.ConfigHttp.jsonpost(self)
        return Result
    def herdersHandle(self, header, herderList):  # 动态头部信息获取
        '''
        :param header: 前端传入的头部信息
        :param herderList: 多个头部列表信息
        :return:如果参数“header”不为空，包含“$”符号，则进行动态参数赋值，
                没有“$”符号则是前端填入的值，
                如果“header”为空则为“{}”字典类型的空值
        '''

        if header != "":
            if "$" in str(header):
                if not isinstance(herderList, list):
                    herderList = eval(herderList)
                for i in range(len(herderList)):
                    if str(herderList[i]["headerName"]) == str(header):
                        herderVaruse = DolphinTestHeards.objects.filter(id=herderList[i]["headerValues"])
                        headerValues = herderVaruse.values("headrsValues")[0]["headrsValues"]

                        self.headers = eval(headerValues)
            else:
                self.headers = eval(header)
        self.headers.update({'Connection': 'close'})  # 禁止长链接

    def getAddress(self, requestId, num):  # 查库
        '''
        :param requestId:前端传入的接口ID
        :param num:int类型，前置关联接口调用“1”，当前case接口调用“2”
        :return:
        '''
        requestObj = DolphinTestRequest.objects.filter(request_id=requestId)
        groupList = DolphinTestGrouping.objects.filter(
            group_id=requestObj.values("request_group_id")[0]["request_group_id"])
        projectList = DolphinTestProject.objects.filter(
            pj_id=groupList.values("group_pj_id")[0]["group_pj_id"])
        url1 = projectList.values("pj_running_address")[0]["pj_running_address"]
        if num == 1:
            url3 = projectList.values("configure_address")[0]["configure_address"]
            url4 = projectList.values("otherconfigure")[0]["otherconfigure"]
            return {"url1": url1, "url2": url3, "url4": url4}
        if num == 2:
            url2 = requestObj.values("request_address")[0]["request_address"]
            request_mode = requestObj.values("request_mode")[0]["request_mode"]
            return {"url1": url1, "url2": url2, "request_mode": request_mode}

    def getModedate(self, data1):  # 整理传参的值
        """
        :param data1:请求的接口的值
        :return: 返回已经整理过后的入参值
        """
        for b in range(len(list(data1))):  # 循环请求入参中的个数
            listruet = list(self.reusltlist.keys())  # 获取列表中的键的值
            for c in range(len(listruet)):  # 循环全部键的长度
                if listruet[c] == str(list(data1.values())[b]):  # 当键的值 等于入参的值相等时
                    dicc = {str(list(data1.keys())[b]): str(self.reusltlist[listruet[c]])}
                    data1.update(dicc)
        return data1

    def getSQLValue(self, id, sql, SQLMomentum, reusltList):
        """
        :param id: 数据库ID
        :param sql: SQL语句
        :param SQLMomentum:SQL动量参数
        :param reusltList: 关联动态动态接口取值
        :return: 返回SQL结果
        """
        if SQLMomentum != "":
            SQLMomentumList = list(SQLMomentum.split(','))
            for i in range(len(reusltList)):
                for j in range(len(SQLMomentumList)):
                    if SQLMomentumList[j] == str(list(reusltList.keys())[i]):
                        SQLMomentumList[j] = str(list(reusltList.values())[i])
            for k in range(len(SQLMomentumList)):
                sql = sql.replace("%s", SQLMomentumList[k], 1)
            logger.info(("sql:", sql))

        sqlRustl = getSql(id=id, sql=sql)
        return sqlRustl
